﻿<link href="@Url.Content("/content/styles/order.css")" rel="stylesheet" type="text/css" />
<style>
    .divTitle { line-height: 35px; margin-bottom: 5px; padding: 0px 5px; display: none; position: relative; }
    .divTitle button { position: absolute; right: 5px; top: 3px; }
    .divTitle span { margin-right: 30px; }
</style>
<div class="ld-tabs">
    <ul>
        <li class="k-state-active">未完成的单据</li>
        <li>填写新的 @LuxDiner.Web.Management.Common.GetOrderName(ViewBag.Method)</li>
    </ul>

    <div>
        <div class="k-block divToolbar">
            <span class="k-textbox k-space-right">
                <input type="text" placeholder="请输入单据号" id="txtKey" />
                <a href="javascript:FilterJyOrders()" class="k-icon k-i-search">&nbsp;</a>
            </span>
            <div style="display: inline-block;">
                <input id="txtCustomer" data-value="0" style="width: 300px" />
            </div>
            <br />
            <br />
            <div style="display: inline-block;">
                <input id="txtOrderDateBefore" class="date" placeholder="开始时间" />
            </div>
            --
            <div style="display: inline-block;">
                <input id="txtOrderDateAfter" class="date" placeholder="结束时间" />
            </div>
            <button class="k-button" onclick="FilterJyOrders()"><span class="k-icon k-i-search"></span><span>搜索</span></button>
        </div>
        <div id="grid_orders_jy"></div>
    </div>

    <div>
        <div class="k-block form_title">

            <div style="display: inline-block;">
                <b>仓库：</b><input id="txtWarehouse" data-value="0" style="width: 200px;" />
            </div>
            <div style="display: inline-block;">
                <b>日期：</b><input id="txtNoteDate" />
            </div>
        </div>
        <div class="k-block divTitle">
            <b>单据号：</b><span id="lblOrderNo" data-value="0"></span>
            <b>客户：</b><span id="lblCustomer"></span>
            <b>状态：</b><span id="lblOrderStatus"></span>
            <b>日期：</b><span id="lblNoteDate"></span>
            <button class="k-button" onclick="SaveChanges()">
                <span class="k-icon k-i-tick"></span><span>保存 @LuxDiner.Web.Management.Common.GetOrderName(ViewBag.Method)</span>
            </button>
        </div>
        <div id="grid_orders"></div>
    </div>
</div>
<script class="init">
    var submenu;
    @if (ViewBag.Method == 11)
    {
        <text>submenu = "新入库单";</text>
    }
    else if (ViewBag.Method == 12)
    {
        <text>submenu = "新出库单";</text>
    }
    LocatedMenu("仓库管理", submenu);
</script>
<script class="grid_order_jy">
    var jyOrdersFields = [{
        title: "单据号",
        field: "OrderNo",
        template: "#=GetOperations(OrderNo)#",
        width: 130
    }, {
        title: "客户",
        field: "Customer.Corporation",
        width: 300
    }, {
        title: "状态",
        field: "OrderStatus",
        template: "#=GetOrderStatusString(OrderStatus,Method)#",
        width: 100
    }, {
        title: "日期",
        template: "#=kendo.toString(kendo.parseDate(NoteDate),'yyyy-MM-dd')#",
        width: 100
    }, {}];

    function GetOperations(orderNo) {
        var html = "<a href=\"javascript:JumpToProductOrder('" + orderNo + "')\">" + orderNo + "</a>";
        return html;
    }

    $(function () {
        $("#grid_orders_jy").kendoGrid({
            columns: jyOrdersFields,
            dataSource: Whale.dataSource({
                url: "/Orders/DealOrder/GetOrders",
                getParameters: function () {
                    return {
                        getCustomer: true,
                        customerID: $("#txtCustomer").attr("data-value"),
                        orderDateBefore: $("#txtOrderDateBefore").val(),
                        orderDateAfter: $("#txtOrderDateAfter").val(),
                        orderNo: $("#txtKey").val(),
                        orderMethod: "@(ViewBag.Method == (int)LuxDiner.Model.Orders.OrderMethod.RK ? "1,4" : "2,3")",
                        orderStatus: "1,3"
                    };
                },
                pageSize: 20

            }),
            pageable: {
                messages: {
                    empty: "暂无数据"
                }
            },
            dataBound: function (e) {
                //让表头居中
                $("th.k-header").attr("style", "text-align:center; font-weight:bold;");
            }
        });
    });

    function FilterJyOrders() {
        $("#grid_orders_jy").data("kendoGrid").dataSource.read();
    }
</script>

<script class="init">
    $("#txtNoteDate").kendoDatePicker({
        value: new Date(),
        culture: "zh-CHS",
        format: "yyyy年MM月dd日",
    });

    $("#txtWarehouse").kendoComboBox({
        placeholder: "请选择仓库...",
        filter: "contains",
        dataTextField: "House",
        dataValueField: "ID",
        dataSource: Whale.dataSource({
            url: "/Orders/Warehouse/Gets"
        }),
        select: function (e) {
            var item = this.dataItem(e.item.index());
            $("#txtWarehouse").attr("data-value", item.ID);
        },
        change: function (e) {
            if (!$.isNumeric(this.value())) {
                $("#txtWarehouse").attr("data-value", 0);
            } else {
                $.map(orderDataSource.data(), function (o) {
                    var rep = Whale.Remote.GetCollection({
                        url: "/Orders/Repertory/GetTops",
                        parameters: {
                            productID: o.Product.ID,
                            houseID: $("#txtWarehouse").attr("data-value")
                        }
                    });
                    if (rep != null && rep.Success) {
                        $.map(rep.Data, function (r) {
                            if (r.Balance >= o.Quantity)
                                o.Retention = r.Retention;
                        });
                    }
                });
                $("#grid_orders").data("kendoGrid").refresh();
            }
        }
    });

    $("#txtCustomer").kendoComboBox({
        placeholder: "请选择客户...",
        filter: "contains",
        dataTextField: "Pinyin",
        template: "#=ComplexName#",
        dataValueField: "ID",
        dataSource: Whale.dataSource({
            url: "/Members/Customer/Gets",
            getParameters: function () {
                return {
                    key: $.trim($("#txtCustomer").data("kendoComboBox").text()),
                    cType: "@((ViewBag.Method == (int)LuxDiner.Model.Orders.OrderMethod.RK) ? 2 : 1)"
                };
            },
        }),
        change: function (e) {
            if ($.isNumeric(this.value())) {
                var item = this.dataItem();
                $("#txtCustomer").attr("data-value", item.ID);
                this.text(item.ComplexName);
                FilterJyOrders();
            } else if (this.text() == "") {
                $("#txtCustomer").attr("data-value", 0);
                FilterJyOrders();
            }
        }
    });

    $(".date").kendoDatePicker({
        culture: "zh-CHS",
        format: "yyyy年MM月dd日",
    });
</script>

<script class="grid_orders_columns">
    var orderFields = [{
        title: "商品名称",
        field: "Product",
        template: "#=Product.ProductName#",
        width: 260
    }, {
        title: "单位",
        field: "Product",
        template: "#=Product.UnitName#",
        width: 100
    }, {
        title: "数量",
        field: "Quantity",
        editor: quantityEditor,
        width: 100
    }, {
        title: "备注",
        field: "AssistantQuantity",
        width: 100
    @if (ViewBag.Method == (int)LuxDiner.Model.Orders.OrderMethod.RK)
    {
        <text>
    }, {
        title: "费用",
        field: "Amount",
        format: "{0:c}",
        editor: amountEditor,
        width: 100
        </text>
    }
    }, {
        title: "批号",
        field: "Retention",
        editor: retentionSelectEditor,
        width: 100
    }, {
        title: "操作",
        command: [{
            name: "destroy",
            text: "删除"
        }]
    }];

    function quantityEditor(container, options) {
        var txtQuantity = $('<input required data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoNumericTextBox({
                max: options.model.Quantity,
                min: 0,
                change: function (e) {
                    options.model.Quantity = txtQuantity.value();
                    var rate = options.model.Product.AssistantUnitRate;
                    if (rate != null && rate > 0) {
                        var q = options.model.Quantity;
                        var d = Math.floor(q / rate);
                        var m = q % rate;
                        if (d > 0) {
                            options.model.AssistantQuantity = d + options.model.Product.AssistantUnitName;
                            if (m > 0)
                                options.model.AssistantQuantity += m + options.model.Product.UnitName;
                        }
                    }
                    $("#grid_orders").data("kendoGrid").refresh();
                }
            }).data("kendoNumericTextBox");
    }

    function amountEditor(container, options) {
        var txtPrice = $('<input data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoNumericTextBox({
                format: "{0:c}"
            }).data("kendoNumericTextBox");
    }

    ///入库时，批号输入
    function retentionInputEditor(container, options) {
        var txtRetention = $('<input data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoDatePicker({
                depth: "year",
                start: "year",
                culture: "zh-CHS",
                format: "yyyyMM",
            }).data("kendoDatePicker");
    }

    ///出库时，批号选择
    function retentionSelectEditor(container, options) {
        var houseID = $("#txtWarehouse").attr("data-value");
        if (houseID > 0) {
            var selRetention = $('<select data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoComboBox({
                //autoBind: true,
                dataTextField: "Retention",
                dataValueField: "Retention",
                dataSource: Whale.dataSource({
                    url: "/Orders/Repertory/GetTops",
                    getParameters: function (e) {
                        return {
                            productID: options.model.Product.ID,
                            houseID: houseID,
                            repType: 3,
                            hideZero: true
                        }
                    }
                }),
                //dataBound: function (e) {
                //    var item = e.sender.dataItem();
                //    if (item != null)
                //        options.model.Retention = item.Retention;
                //},
                change: function (e) {
                    var item = selRetention.dataItem();
                    if (item != null && item != undefined) {
                        options.model.Retention = item.Retention;
                    }
                }
            }).data("kendoComboBox");
        } else {
            wndGeneralInformation.content("请先选择一个仓库。").open();
        }
    }
</script>

<script class="grid_orders_config">
    var orderDataSource = new kendo.data.DataSource({
        schema: {
            model: {
                fields: {
                    Product: { editable: false },
                    Quantity: { validation: { required: true } },
                    Retention: {},
                    AssistantQuantity: { editable: false }
                }
            }
        }
    });

    $("#grid_orders").kendoGrid({
        columns: orderFields,
        pageable: false,
        editable: true,
        dataBound: function (e) {
            //让表头居中
            $("th.k-header").attr("style", "text-align:center; font-weight:bold;");
        },
        dataSource: orderDataSource
    });
</script>

<script class="functions">
    ///调出单据
    function JumpToProductOrder(orderNo) {
        //var orderNo = $.trim($("#txtOrderNo").val());
        var jyOrder = Whale.Remote.GetEntity({
            url: "/Orders/DealOrder/GetOrderWithProductOrders",
            parameters: { orderNo: orderNo }
        });
        if (jyOrder != null) {
            if (jyOrder.OrderStatus == 5) {
                wndGeneralInformation.content("对不起，此交易单已完成，不能再操作。").open();
                return;
            }
            $(".divTitle").show();
            $("#lblOrderNo").attr("data-value", jyOrder.ID);
            $("#lblOrderNo").html(jyOrder.OrderNo);
            $("#lblNoteDate").html(kendo.toString(kendo.parseDate(jyOrder.NoteDate), 'yyyy-MM-dd'));
            $("#lblCustomer").html(jyOrder.Customer.Corporation);
            $("#lblOrderStatus").html(GetOrderStatusString(jyOrder.OrderStatus, jyOrder.Method));

            orderDataSource.data(jyOrder.Items);
            $("#grid_orders").data("kendoGrid").setDataSource(orderDataSource);

            $(".ld-tabs").data("kendoTabStrip").select(1);
            return;
        }
        wndGeneralInformation.content("无效的单据").open();
    }

    /// 保存单据
    function SaveChanges() {
        var values = {
            dealOrderID: $("#lblOrderNo").attr("data-value"),
            orderDate: kendo.toString($("#txtNoteDate").data("kendoDatePicker").value(), "yyyy-MM-dd"),
            houseID: $("#txtWarehouse").attr("data-value"),
            method: "@ViewBag.Method",
            orderItems: []
        };

        values.orderItems = $.map(orderDataSource.data(), function (o) {
            return {
                productID: o.Product.ID,
                quantity: o.Quantity,
                costMoney: o.Amount,
                retention: o.Retention
            }
        });
        Whale.Remote.Operation({
            url: "/Orders/ProductOrder/SaveOrders",
            parameters: values,
            success: function (result) {
                location.href = "/Success/PrintProductOrder/" + result.OrderNo;
            },
            error: function (msg) {
                wndGeneralInformation.content(msg).open();
            }
        });
    }
</script>
